
package com.epfresh.supplier.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.utils.FormatUtil;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.AgencyListItem;
import com.epfresh.supplier.entity.BaseProductAreaConfigPrices;
import com.epfresh.supplier.entity.BaseStoreInfo;
import com.epfresh.supplier.entity.BuyerProduct;
import com.epfresh.supplier.entity.GrouponInfo;
import com.epfresh.supplier.entity.HomeBuyer;
import com.epfresh.supplier.view.tag.FlowLayout;
import com.epfresh.supplier.view.tag.TagAdapter;
import com.epfresh.supplier.view.tag.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import multitype.ItemViewBinder;
import multitype.OnRecyclerViewItemClickListener;

public class GrouponInfoViewBinder
        extends ItemViewBinder<GrouponInfo, GrouponInfoViewBinder.ViewHolder> implements View.OnClickListener {

    View vBottom;
    View vRecommend;
    ViewHolder vh;

    boolean isRecommend;
    AgencyListItem agencyListItem;
    boolean isSingle;
    EditText mEtAmount;
    public interface OnBuyerListener {
        void onBuyer(View view, int position, GrouponInfo data);
    }


    View.OnClickListener onRecommendListener;
    OnBuyerListener onBuyerListener;
    OnBuyerListener onDateListener;
    OnBuyerListener onAgentListener;
    OnRecyclerViewItemClickListener onRecyclerViewItemClickListener;

    public OnBuyerListener getOnAgentListener() {
        return onAgentListener;
    }

    public boolean isSingle() {
        return isSingle;
    }

    public void setSingle(boolean single) {
        isSingle = single;
    }

    public void setOnAgentListener(OnBuyerListener onAgentListener) {
        this.onAgentListener = onAgentListener;
    }

    public OnBuyerListener getOnDateListener() {
        return onDateListener;
    }

    public void setOnDateListener(OnBuyerListener onDateListener) {
        this.onDateListener = onDateListener;
    }

    public AgencyListItem getAgencyListItem() {
        return agencyListItem;
    }

    public String getAmount(){
        return mEtAmount.getText().toString();
    }
    public void setAgencyListItem(AgencyListItem agencyListItem) {
        this.agencyListItem = agencyListItem;
    }

    public View.OnClickListener getOnRecommendListener() {
        return onRecommendListener;
    }

    public void setOnRecommendListener(View.OnClickListener onRecommendListener) {
        this.onRecommendListener = onRecommendListener;
    }

    public OnBuyerListener getOnBuyerListener() {
        return onBuyerListener;
    }

    public void setOnBuyerListener(OnBuyerListener onBuyerListener) {
        this.onBuyerListener = onBuyerListener;
    }

    public OnRecyclerViewItemClickListener getOnRecyclerViewItemClickListener() {
        return onRecyclerViewItemClickListener;
    }

    public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener onRecyclerViewItemClickListener) {
        this.onRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
    }

    @NonNull
    @Override
    protected ViewHolder onCreateViewHolder(
            @NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        View view = inflater.inflate(R.layout.item_groupon_info_body, parent, false);
        return new ViewHolder(view);
    }


    @Override
    protected void onBindViewHolder(@NonNull ViewHolder holder, @NonNull GrouponInfo post) {

      /*  holder.rl_base.setTag(R.id.item_key_position, getPosition(holder));
        holder.rl_base.setTag(R.id.item_key_status, post);
        holder.rl_base.setOnClickListener(this);
        holder.rl_product.setTag(R.id.item_key_position, getPosition(holder));
        holder.rl_product.setTag(R.id.item_key_status, post);
        holder.rl_product.setOnClickListener(this);

        holder.tv_product_new.setTag(R.id.item_key_position, getPosition(holder));
        holder.tv_product_new.setTag(R.id.item_key_status, post);
        holder.tv_product_new.setOnClickListener(this);
*/
        vBottom = holder.vBottom;
        vRecommend = holder.vRecommend;

        mEtAmount = holder.etAmount;
        holder.vRecommendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onRecommendListener != null){
                    onRecommendListener.onClick(view);
                }
            }
        });
        holder.tvExceptTime.setTag(R.id.item_key_position, getPosition(holder));
        holder.tvExceptTime.setTag(R.id.item_key_status, post);
        holder.tvExceptTime.setOnClickListener(this);
        holder.tvSelectAgent.setTag(R.id.item_key_position, getPosition(holder));
        holder.tvSelectAgent.setTag(R.id.item_key_status, post);
        holder.tvSelectAgent.setOnClickListener(this);

        if (isSingle){
            holder.ivAgentArrow.setVisibility(View.INVISIBLE);
        }else {
            holder.ivAgentArrow.setVisibility(View.VISIBLE);

        }
        holder.setData(post);
        updateView(isRecommend);

        vh = holder;
        updateAgency(agencyListItem);
    }

    public void updateAgency(AgencyListItem agencyListItem) {
        this.agencyListItem = agencyListItem;
        if (agencyListItem != null && vh != null){
            vh.tvSelectAgentName.setText(agencyListItem.getConsigneeName() + "  "+agencyListItem.getConsigneePhone());
            vh.tvSelectAgentAddress.setText(agencyListItem.getConsigneeAddress());
            vh.tvSelectStoreName.setText(agencyListItem.getName());
        }
    }


    public void updateView(boolean isRecommend) {
        this.isRecommend = isRecommend;
        if (vBottom != null && vRecommend != null) {
            if (isRecommend){
                vBottom.setVisibility(View.GONE);
                vRecommend.setVisibility(View.VISIBLE);
            }else {
                vRecommend.setVisibility(View.GONE);
                vBottom.setVisibility(View.VISIBLE);

            }
        }
    }
    @Override
    public void onClick(View v) {

        Object tag = v.getTag(R.id.item_key_position);
        if (tag != null && tag instanceof Integer) {
            int position = (int) tag;
            Object o = v.getTag(R.id.item_key_status);


            switch (v.getId()) {
                case R.id.tv_product_new:

                    if (onBuyerListener != null && o instanceof GrouponInfo) {
                        onBuyerListener.onBuyer(v, position, (GrouponInfo) o);
                    }
                    break;
                case R.id.tv_except_time:

                    if (onDateListener != null && o instanceof GrouponInfo) {
                        onDateListener.onBuyer(v, position, (GrouponInfo) o);
                    }
                    break;
                case R.id.tv_select_angent:

                    if (!isSingle && onAgentListener != null && o instanceof GrouponInfo) {
                        onAgentListener.onBuyer(v, position, (GrouponInfo) o);
                    }
                    break;

                default:
                    if (onRecyclerViewItemClickListener != null && o instanceof GrouponInfo) {
                        onRecyclerViewItemClickListener.onItemClick(v, position, o);
                    }
                    break;
            }


        }
    }


    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivProduct;
        TextView tvStoreName;
        TextView tvProductTitle;
        TextView tvProductPrice;
        TextView tvProductPackage;
        TextView tvProductAlreadySize;
        TextView tvProductSize;
        TextView tvDeposit;
        TextView tvDeliveryDate;
        TextView tvSelectAgent;
        TextView tvSelectAgentName;
        TextView tvSelectAgentAddress;
        ImageView tvSelectAgentMap;
        TextView tvSelectStoreName;
        TextView tvExceptDate;
        TextView tvExceptTime;
        TextView tvAmountUnit;
        EditText etAmount;
        View vBottom;
        View vRecommend;
        View vRecommendBtn;
        TagFlowLayout mTflBuyerPrice;
        ImageView ivArrow;
        ImageView ivAgentArrow;
        List<BaseProductAreaConfigPrices> mPriceList = new ArrayList<>();
        List<BaseProductAreaConfigPrices> mPriceListAll = new ArrayList<>();
        TagAdapter<BaseProductAreaConfigPrices> mPriceAdapter;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvStoreName = itemView.findViewById(R.id.tv_store_title);
            ivProduct = itemView.findViewById(R.id.iv_product);
            tvProductTitle = itemView.findViewById(R.id.tv_product_title);
            tvProductPrice = itemView.findViewById(R.id.tv_product_price);
            tvProductPackage = itemView.findViewById(R.id.tv_product_package);
            tvProductAlreadySize = itemView.findViewById(R.id.tv_product_already_size);
            tvProductSize = itemView.findViewById(R.id.tv_product_size);
            tvDeposit = itemView.findViewById(R.id.tv_deposit);
            mTflBuyerPrice = itemView.findViewById(R.id.tfl_buyer_price);
            ivArrow = itemView.findViewById(R.id.iv_product_bottom_arrow);
            ivAgentArrow = itemView.findViewById(R.id.iv_agent_arrow);
            tvDeliveryDate = itemView.findViewById(R.id.tv_delivery_date);
            tvSelectAgent = itemView.findViewById(R.id.tv_select_angent);

            tvSelectAgentName = itemView.findViewById(R.id.tv_select_angent_name);
            tvSelectAgentAddress = itemView.findViewById(R.id.tv_select_address);
            tvSelectAgentMap = itemView.findViewById(R.id.iv_select_agent_map);
            tvSelectStoreName = itemView.findViewById(R.id.tv_select_store_name);
            tvAmountUnit = itemView.findViewById(R.id.tv_buy_amount_unit);
            etAmount = itemView.findViewById(R.id.et_amount);
            tvExceptDate = itemView.findViewById(R.id.tv_expect_date);
            tvExceptTime = itemView.findViewById(R.id.tv_except_time);
            vBottom = itemView.findViewById(R.id.v_bottom_bg);
            vRecommend = itemView.findViewById(R.id.rl_commend);
            vRecommendBtn = itemView.findViewById(R.id.tv_recommend_btn);

            ivArrow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ivArrow.getVisibility() == View.VISIBLE) {
                        expendPrice();
                    }
                }
            });


        }


        void setData(GrouponInfo post) {


            BuyerProduct p = post.getProduct();
            BaseStoreInfo baseStore = post.getBaseStore();


            String chargeUnit = "";
            if (p != null) {
                tvProductTitle.setText(p.getTitle());

                chargeUnit = p.getChargeUnit();
                if (baseStore != null) {
                    tvStoreName.setText(baseStore.getName());
                } else {
                    tvStoreName.setText("");
                }

                ImageLoader.getInstance().displayImage(p.getImgUrl(),ivProduct);

                tvProductPrice.setText(p.getPriceRangeStr());
//                定金30%  尾款70%
                String deposit = p.getDeposit();
                String depositLast = p.getDepositLast();


                deposit = "订金" + deposit + "%  尾款" + depositLast + "%";

                tvDeposit.setText(deposit);

                tvProductPackage.setText(p.getPack());

                String s = "满" + FormatUtil.subZeroAndDot(p.getMinOrderQuantity()) + chargeUnit + "发货，可拼" + FormatUtil.subZeroAndDot(p.getMaxOrderQuantity()) + chargeUnit;
                tvProductAlreadySize.setText(s);


                s = "已拼" + FormatUtil.subZeroAndDot(p.getSumProductCount()) + chargeUnit + "（还剩：" + FormatUtil.subZeroAndDot(FormatUtil.countAdd(p.getMaxOrderQuantity(), p.getSumProductCount())) + chargeUnit+"）";
                tvProductSize.setText(s);

                tvDeliveryDate.setText(post.getDeliveryInfo());
            }


            etAmount.setText(post.getProductCount());
            tvAmountUnit.setText(chargeUnit);
            tvExceptDate.setText(post.getDeliveryDate());

            if (mPriceAdapter == null) {
                mPriceAdapter = new TagAdapter<BaseProductAreaConfigPrices>(mPriceList) {
                    @Override
                    public View getView(FlowLayout parent, int position, BaseProductAreaConfigPrices baseProductAreaConfigPrices) {
                        View v = LayoutInflater.from(itemView.getContext()).inflate(R.layout.tfl_item_product_price,
                                parent, false);
                        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
                        lp.width = (LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(24)) / 3;

                        TextView tvPrice = v.findViewById(R.id.tv_price);
                        TextView tvUnit = v.findViewById(R.id.tv_unit);
                        View vLine = v.findViewById(R.id.v_line);
                        String p = FormatUtil.subZeroAndDot(baseProductAreaConfigPrices.getPrice()) + "元/" + baseProductAreaConfigPrices.getChargeUnit();
                        tvPrice.setText(p);
                        tvUnit.setText(baseProductAreaConfigPrices.getOrderQuantityRange());
                        if (position == mPriceList.size() - 1 || position % 3 == 2) {
                            vLine.setVisibility(View.GONE);
                        } else {
                            vLine.setVisibility(View.VISIBLE);
                        }

                        return v;
                    }
                };
                mPriceList.clear();
                mPriceListAll.clear();

                List<BaseProductAreaConfigPrices> prices = post.getPrices();
                if (prices != null) {
                    for (int i = 0; i < prices.size(); i++) {
                        BaseProductAreaConfigPrices b = prices.get(i);
                        b.setChargeUnit(chargeUnit);
                        mPriceListAll.add(b);
                    }
                }
                updatePriceList(false);
                mTflBuyerPrice.setAdapter(mPriceAdapter);


            }
        }

        private void expendPrice() {

            if (mPriceList.size() > 3) {
                updatePriceList(false);
            } else {
                updatePriceList(true);
            }

            mPriceAdapter.notifyDataChanged();

        }

        private void updatePriceList(boolean isExpend) {
            mPriceList.clear();
            int size = mPriceListAll.size();
            if (size < 3) {
                ivArrow.setVisibility(View.INVISIBLE);
            }
            if (!isExpend) {
                ivArrow.setImageResource(R.mipmap.icon_base_product_up_arrow);
                size = size > 3 ? 3 : size;
            } else {
                ivArrow.setImageResource(R.mipmap.icon_base_product_down_arrow);
            }
            for (int i = 0; i < size; i++) {
                mPriceList.add(mPriceListAll.get(i));
            }
        }

    }
}
